package com.huluobo.a2208kotlindouyindemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2208kotlindouyindemo.MainActivity
import com.huluobo.a2208kotlindouyindemo.R
import com.huluobo.a2208kotlindouyindemo.databinding.ActivityLoginBinding
import com.huluobo.base.bean.Money
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {
    override fun initData() {
        vm.loginSuccess.observe(this) {
            ToastUtils.showLong("欢迎回来:${it.username}")
            SPUtils.getInstance().put(Const.PARAM_USERNAME, it.username)
            SPUtils.getInstance().put(Const.PARAM_PASSWORD, it.password)
            SPUtils.getInstance().put(Const.PARAM_TOKEN, it.token)
            val money = Money(username = it.username, money = 10000F)
            vm.insertMoney(money)
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

    override fun initView() {
        binding.loginBtn.setOnClickListener {
            val username = binding.loginUsernameEt.text.toString()
            val password = binding.loginPasswordEt.text.toString()

            if (username.isNotEmpty() && password.isNotEmpty()) {
                val map = mutableMapOf<String, String>()
                map[Const.PARAM_USERNAME] = username
                map[Const.PARAM_PASSWORD] = password

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                vm.login(body)
            }
        }
    }
}